package cn.gson.crm.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.gson.crm.model.dao.SgfDAO;
import cn.gson.crm.model.pojo.ConstactOrder;
import cn.gson.crm.model.pojo.Customerinfo;
import cn.gson.crm.model.pojo.Sendgoodsform;
import cn.gson.crm.model.vo.ConstactOrderVO;
import cn.gson.crm.model.vo.CustomerVO;
import cn.gson.crm.model.vo.SgfVO;

@Service
@Transactional
public class SgfService {

	@Autowired
	private SgfDAO sgfDAO;

	/**
	 * 获取所有发货单
	 * 
	 * @param page
	 * @param rows
	 * @return
	 */
	public List<SgfVO> getAllSgf(int page, int rows) {
		PageRequest pageable = new PageRequest(page - 1, rows);
		List<Sendgoodsform> listpo = sgfDAO.getAllSgf(pageable);
		List<SgfVO> listvo = new ArrayList<>();
		for (Sendgoodsform s : listpo) {
			listvo.add(returnSgfVo(s));
		}
		return listvo;
	}

	public SgfVO returnSgfVo(Sendgoodsform s) {
		SgfVO sgfVO = new SgfVO(s.getSgfId(), s.getSgfCoId(), s.getSgfCoTheme(), s.getSgfCusId(), s.getSgfCusName(),
				s.getSgfFare(), s.getSgfSendMan(), s.getSgfTime(), s.getSgfWay());
		Customerinfo customerinfo = s.getCustomerinfo();
		ConstactOrder constactOrder = s.getConstactOrder();
		if (customerinfo != null) {
			CustomerVO cVo = new CustomerVO(customerinfo.getCustId(), customerinfo.getCustName());
			sgfVO.setCustomerVO(cVo);
			sgfVO.setCusVoId(cVo.getCustId());
			sgfVO.setCusVoName(cVo.getCustName());
		}
		if (constactOrder != null) {
			ConstactOrderVO cOrderVO = new ConstactOrderVO(constactOrder.getCoId(), constactOrder.getCoTheme());
			sgfVO.setConstactOrderVO(cOrderVO);
			sgfVO.setOrderVoId(cOrderVO.getCoId());
			sgfVO.setOrderVoTheme(cOrderVO.getCoTheme());
		}
		return sgfVO;
	}

	public Long count() {
		return sgfDAO.count();
	}
	
	public void deleteSgf(Long id) {
		try {
			sgfDAO.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
}
